﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Vowei.Data.Models;
using System.Diagnostics;
using Vowei.Core;
using Vowei.Web;

namespace vowei.web.Controllers
{
    // TODO: 在第一个预览版实现以后,考虑是否还要这个类,还是升级到其它形式
    public class SetupController : G18nController
    {
        public ActionResult SetupSite()
        {
            CreateBuiltInUserAndRoles();

            return Redirect("/");
        }

        public ActionResult ResetSite()
        {
            var usernames = new string[] 
            {
                Constants.BuiltIn.Users.Administrator
            };

            foreach (var user in usernames)
            {
                if (Membership.FindUsersByEmail(user) != null)
                    Membership.DeleteUser(user);
            }


            var type = typeof(Constants.BuiltIn.Roles);
            var fields = type.GetFields();

            foreach (var field in fields)
            {
                var roleName = field.GetValue(null) as string;
                if ( Roles.RoleExists(roleName) )
                    Roles.DeleteRole(roleName);
            }

            return Redirect("/");
        }

        private void CreateBuiltInUserAndRoles()
        {
            CreateBuiltInUsers();
            CreateBuiltInRoles();

            // TODO: 默认情况下给管理员分配“项目经理”这个权限集
            Roles.AddUserToRole(Constants.BuiltIn.Users.Administrator,
                Constants.BuiltIn.Roles.Administrators);
        }

        private void CreateBuiltInRoles()
        {
            var type = typeof(Constants.BuiltIn.Roles);
            var fields = type.GetFields();

            foreach (var field in fields)
            {
                var roleName = field.GetValue(null) as string;
                Debug.Assert(roleName != null);
                Roles.CreateRole(roleName);
            }
        }

        private void CreateBuiltInUsers()
        {
            var usernames = new string[] 
            {
                Constants.BuiltIn.Users.Administrator
            };
            
            foreach (var username in usernames)
            {
                Membership.CreateUser(username, username, username);
            }
        }
    }
}
